<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form>
        <a-row :gutter="24">
          <a-col :span="3">
            <a-form-item label="类型">
              <a-select v-model:value="queryParams.type" allowClear placeholder="选择数据类型">
                <a-select-option value="page">页面</a-select-option>
                <a-select-option value="report">报表</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="4" :offset="1">
            <a-form-item label="编码">
              <a-input placeholder="请输入标识编码" v-model:value="queryParams.code"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="4" :offset="1">
            <a-form-item label="名称">
              <a-input placeholder="请输入页面或报表名字" v-model:value="queryParams.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5" :offset="1">
            <a-form-item>
              <a-button type="primary" @click="searchQuery"><SearchOutlined/>查询</a-button>
              <a-button type="primary" @click="searchReset" style="margin-left: 30px"><ReloadOutlined/>重置</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
        <a-button @click="handleAdd" type="primary"><PlusOutlined/>新建</a-button>
        <a-button style="margin-left: 8px" danger v-if="selectedRowKeys.length > 0 && currentUser.isAdmin"
                  @click="() => handleDelete(selectedRowKeys)">删除<DeleteOutlined/>
        </a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-alert type="info" show-icon>
          <template #message>
            <div>
              已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a> 项
              <a style="margin-left: 24px" @click="onClearSelected">清空</a>
            </div>
          </template>
      </a-alert>
      <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :sorter="tableSorter"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange">
        <template #action="{ text, record }">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>更多<DownOutlined /></a>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="popReportURL(record)">
                  配置地址
                </a-menu-item>
                <a-menu-item>
                  <a @click="goPageOnline(record)">功能测试</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="handleClone(record)">复制</a>
                </a-menu-item>
                <a-menu-item>
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->
    <!-- 表单区域 -->
    <CustomReportModal ref="configModal" @ok="handleOk"></CustomReportModal>
    <!-- 提示online报表链接 -->
    <a-modal ref="urlModal"
        title="报表访问链接"
        :open="visible"
        @cancel="handleCancel">
      <template #footer>
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" class="copy-this-text" :data-clipboard-text="reportUrlText" @click="onCopyUrl">复制</a-button>
      </template>
      <p>{{ reportUrlText }}</p>
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import Clipboard from 'clipboard';
import CustomReportModal from "@/views/modules/basicModal/CustomReportModal.vue";
import { useRouter } from 'vue-router'
import { deleteOPageById, getOnlinePages } from "@/utils/api.js";
import { commonConf } from "@/utils/my.js";
import _ from 'lodash';
import useUserStore from "@/store/modules/user.js";

const currentUser = useUserStore()

// 路由实例
const router = useRouter();

// 响应式数据
const configModal = ref(null);
const urlModal = ref(null);
const visible = ref(false);
const title = ref('');
const reportUrlText = ref('');
const selectedRowKeys = ref([]);
const loading = ref(false);
const dataSource = ref([]);

////reactive+refs
const data = reactive({
  queryParams: { type: '', code: '', name: '' },
  ipagination: commonConf("ipagination")
});
const { queryParams, ipagination} = toRefs(data);
const tableSorter = ref({})

// 表格列定义
const columns = [
  {
    title: '名称', align: 'left', dataIndex: 'name', sorter: true,
  },
  {
    title: '编码', align: 'left', dataIndex: 'code', sorter: true,
  },
  {
    title: '查询SQL', align: 'left', width: '40%', dataIndex: 'sql'
  },
  {
    title: '描述', align: 'left', dataIndex: 'memo'
  },
  {
    title: '创建时间', align: 'center', dataIndex: 'create_time', sorter: true,
  },
  {
    title: '操作', dataIndex: 'action', align: 'center',
    slots: { customRender: 'action' }
  }
];

// 方法定义
function getUrlText(record) {
  let page = '';
  if(record.type ==='page'){
     page = 'page';
  }else if(record.type ==='report'){
     page = 'report'
  }
  let code = record.code;
  // id = btoa(id);
  return `/${page}?code=${code}`;
}

function goPageOnline(record) {
  // console.error(JSON.stringify(record))
  router.push(getUrlText(record));
}

function popReportURL(record) {
  visible.value = true;
  reportUrlText.value = window.location.host + getUrlText(record)
}

function handleCancel() {
  visible.value = false;
  reportUrlText.value = '';
}

function handleClone(record) {
  title.value = "复制";
  configModal.value.disableSubmit = false;
}

function onCopyUrl() {
  const clipboard = new Clipboard('.copy-this-text');
  clipboard.on('success', () => {
    clipboard.destroy();
    message.success('复制成功');
    handleCancel();
  });
  clipboard.on('error', () => {
    message.error('该浏览器不支持自动复制');
    clipboard.destroy();
  });
}

function handleOk() {
  // 刷新表格数据
  searchQuery();
}

const onClearSelected = () => {
  selectedRowKeys.value = [];
}

const handleTableChange = (pagination, filters, sorter) => {
  ipagination.value = pagination;
  searchQuery(_.pick(sorter, ['field', 'order']));
}

const handleAdd = () => {
  title.value = "新增";
  configModal.value.goAdd();
}

const handleEdit = (rec) => {
  title.value = "编辑";
  configModal.value.goEdd(rec);
}

const searchQuery = (sorter) => {
  getOnlinePages({...queryParams.value, ...ipagination.value, ...sorter}).then((res)=>{
      dataSource.value = res.data.rows;
      ipagination.value.total = res.data.count;
  })
  tableSorter.value = sorter;
}

const searchReset = () => {
  queryParams.value = { type: '', code: '', name: '' };
  dataSource.value = []
}

const handleDelete = (id) => {
  // console.error("id:",id)
  deleteOPageById(id);
  searchQuery()
}

const onSelectChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys;
}


// 生命周期钩子
onMounted(() => {
  // 初始化逻辑
});
</script>

<style lang="less" scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px
}

.ant-btn-danger {
  background-color: #ffffff
}

.ant-modal-cust-warp {
  height: 100%
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden
}
</style>
